package com.liachen.stock.ext.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.liachen.common.constant.Constant;
import com.liachen.common.util.ToolsUtil;
import com.liachen.stock.entity.Annual;
import com.liachen.stock.ext.CnInfoService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 巨潮信息网
 *
 * @author chen.liang
 * @date 2020/8/31 18:13
 * @since V1.0
 */
@Service
@Slf4j
public class CnInfoServiceImpl implements CnInfoService {
    private static final String CN_INFO_HOST = "http://www.cninfo.com.cn";
    private static final String QUERY_ANNUAL_URL = "/new/hisAnnouncement/query";
    private static final String DOWNLOAD_HOST = "http://static.cninfo.com.cn/";

    @Override
    public Annual queryAnnual(String searchKey, String category) throws IOException {
        String beginDateStr = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), -60), DatePattern.NORM_DATE_PATTERN);
        String endDateStr = DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN);
        String seDate = String.format("%s~%s", beginDateStr, endDateStr);
        FormBody formBody = new FormBody.Builder()
                .add("pageNum", "1")
                .add("pageSize", "30")
                .add("column", "szse")
                .add("tabName", "fulltext")
                .add("searchkey", searchKey)
                .add("category", StringUtils.isEmpty(category) ? "category_ndbg_szsh" : category)
                .add("seDate", seDate)
                .add("isHLtitle", "true")
                .build();
        Request request = new Request.Builder()
                .url(CN_INFO_HOST + QUERY_ANNUAL_URL)
                .method("POST", formBody)
                .build();
        Response response = ToolsUtil.getClient().newCall(request).execute();
        String responseStr = response.body().string();
        Annual annual = JSONObject.parseObject(responseStr, Annual.class);
        return annual;
    }

    @Override
    public void downAnnual(Annual annual) {
        if (annual.getTotalAnnouncement() > 0) {
            annual.getAnnouncements().stream().filter(item -> !item.getAnnouncementTitle().contains("摘要")).forEach(item -> {
                String downLoadPath = DOWNLOAD_HOST + item.getAdjunctUrl();
                String stockName = item.getSecName().replaceAll("<em>", "").replaceAll("</em>", "");
                String name = String.format("%s_%s_%s.pdf", item.getSecCode(), stockName, item.getAnnouncementTitle());
                try {
                    String path = String.format("%s\\%s\\年报", Constant.COMPANY_PATH, stockName);
                    ToolsUtil.mkdir(path);
                    File file = new File(String.format("%s\\%s", path, name));
                    if (!file.exists()) {
                        Request request = new Request.Builder().url(downLoadPath).build();
                        Response response = ToolsUtil.getClient().newCall(request).execute();
                        FileOutputStream outFile =
                                new FileOutputStream(file);
                        outFile.write(response.body().bytes());
                        outFile.close();
                    }

                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            });
        }
    }


}
